# -*- coding: utf-8 -*-
"""
Gunicorn 配置文件
用于 PortAI 应用的多进程部署
"""


# 服务器套接字
bind = "0.0.0.0:8021"
backlog = 2048

# Worker 进程
# workers = multiprocessing.cpu_count() * 2 + 1  # 动态计算worker数量
workers = 4  # 动态计算worker数量
worker_class = "uvicorn.workers.UvicornWorker"  # 使用UvicornWorker支持异步
worker_connections = 1000
timeout = 60 * 30
keepalive = 60 * 30
max_requests = 1000
max_requests_jitter = 50

# 线程
threads = 2

# 日志
accesslog = "8021.log"  # 输出到stdout
errorlog = "8021.log"   # 输出到stderr
loglevel = "info"
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(D)s'

# 进程管理
preload_app = True
daemon = False
pidfile = "gunicorn.pid"
user = None
group = None
tmp_upload_dir = None

# 安全
limit_request_line = 4094
limit_request_fields = 100
limit_request_field_size = 8190

# 性能优化
worker_tmp_dir = "/dev/shm"  # 使用内存文件系统提高性能
capture_output = True
enable_stdio_inheritance = True

# SSL (如果需要HTTPS)
# keyfile = None
# certfile = None

# 环境变量
raw_env = [
    'ENV_FILE=.env',
]

# 进程名称
proc_name = 'portai_server'

# 重启配置
max_worker_memory = 200 * 1024 * 1024  # 200MB
max_worker_lifetime = 3600  # 1小时

def when_ready(server):
    """服务器启动完成时的回调"""
    server.log.info("PortAI 服务器已启动")

def worker_int(worker):
    """Worker进程中断时的回调"""
    worker.log.info("Worker进程被中断")

def pre_fork(server, worker):
    """Fork worker进程前的回调"""
    server.log.info("Worker进程即将启动")

def post_fork(server, worker):
    """Fork worker进程后的回调"""
    server.log.info("Worker进程已启动")

def worker_abort(worker):
    """Worker进程异常退出时的回调"""
    worker.log.info("Worker进程异常退出")
